package com.ezjie.ielts.db;

import java.util.HashSet;
import java.util.Set;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.ezjie.ielts.core.helper.AppDataBaseHelper;
import com.ezjie.ielts.model.AudioFile;

public class AudioFileDB {

	private static AppDataBaseHelper dbHelper;
	private SQLiteDatabase db;

	public AudioFileDB(Context context) {
		dbHelper = AppDataBaseHelper.getInstance(context);
	}

	// 查找科目
	public synchronized AudioFile query(String g_id) {
		db = dbHelper.getReadableDatabase();

		AudioFile info = new AudioFile();
		String sql = "select * from " + AppDataBaseHelper.AUDIOFILE + " where g_id = " + g_id;
		Cursor cursor = db.rawQuery(sql, null);
		while (cursor.moveToNext()) {
			info.g_id = cursor.getString(1);
			info.category_id = cursor.getString(2);
			info.audiofile = cursor.getString(3);
		}
		cursor.close();
		db.close();

		return info;
	}

	// 清楚数据
	public synchronized void claerData() {
		db = dbHelper.getReadableDatabase();
		String sql = "delete from " + AppDataBaseHelper.AUDIOFILE;
		db.execSQL(sql);
	}

	// 查找所有科目
	public synchronized Set<AudioFile> queryList(SQLiteDatabase db) {

		Set<AudioFile> set1 = new HashSet<AudioFile>();
		String sql = "select * from " + AppDataBaseHelper.AUDIOFILE;
		Cursor cursor = db.rawQuery(sql, null);
		while (cursor.moveToNext()) {
			AudioFile info = new AudioFile();
			info.g_id = cursor.getString(1);
			info.category_id = cursor.getString(2);
			info.audiofile = cursor.getString(3);
			set1.add(info);
		}
		cursor.close();

		return set1;
	}

	// 删除科目
	public synchronized void delete() {
		db = dbHelper.getWritableDatabase();

		String sql = "delete from " + AppDataBaseHelper.AUDIOFILE;
		db.execSQL(sql);
		db.close();
	}

	// 更新科目
	public synchronized void update() {
		db = dbHelper.getWritableDatabase();

		String sql = "update " + AppDataBaseHelper.AUDIOFILE + " set audiofile= ? ";
		db.execSQL(sql, new Object[] { 1 });
		db.close();
	}

	/**
	 * 插入科目
	 * 
	 */
	public synchronized void insert(AudioFile audioInfo) {
		db = dbHelper.getWritableDatabase();

		// db.beginTransaction();
		String sql = "insert into " + AppDataBaseHelper.AUDIOFILE + " (g_id,category_id,audiofile) " + "values(?,?,?)";
		db.execSQL(sql, new Object[] { audioInfo.g_id, audioInfo.category_id, audioInfo.audiofile });
		db.close();
	}

	/**
	 * 更新科目
	 * 
	 */
	public synchronized void replaceInto(AudioFile audioInfo) {
		db = dbHelper.getWritableDatabase();

		String sql = "replace into " + AppDataBaseHelper.AUDIOFILE + " (g_id,category_id,audiofile) " + "values(?,?,?)";
		db.execSQL(sql, new Object[] { audioInfo.g_id, audioInfo.category_id, audioInfo.audiofile });

		db.close();
	}

}
